using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 自主构建的特殊点控制器 - 可以在外部直接实例化并自动完成初始化
/// </summary>
public class SpawnPoint : MonoBehaviour
{
    [Header("鸟群生成设置")]
    [Tooltip("鸟预制体")]
    public GameObject boidPrefab;
    [Tooltip("要生成的鸟数量")]
    public int boidCount = 10;
    [Tooltip("生成鸟时的随机半径")]
    public float spawnRadius = 3f;

    [Header("鸟群行为参数")]
    [Tooltip("鸟群环绕半径")]
    public float orbitRadius = 2f;
    [Tooltip("鸟群环绕速度")]
    public float orbitSpeed = 1.5f;
    [Tooltip("特殊点对鸟的吸引力强度")]
    public float attractionStrength = 2f;
    [Tooltip("鸟离特殊点的最大允许距离")]
    public float maxDistance = 15f;

    [Header("检测设置")]
    [Tooltip("每帧检测的鸟数量")]
    public int checksPerFrame = 5;

    // 管理的鸟群
    private List<Boid> managedBoids = new List<Boid>();
    private int currentCheckIndex = 0;
    private Coroutine boundaryCheckCoroutine;

    /// <summary>
    /// 自动构建方法 - 在实例化后由外部调用以完成初始化
    /// </summary>
    /// <param name="boidPrefab">鸟预制体(可选，不传则使用Inspector设置的值)</param>
    /// <param name="boidCount">鸟数量(可选)</param>
    public void Build(GameObject boidPrefab = null, int boidCount = -1)
    {
        // 覆盖默认设置（如果提供了参数）
        if (boidPrefab != null) this.boidPrefab = boidPrefab;
        if (boidCount >= 0) this.boidCount = boidCount;

        // 验证必要组件
        if (this.boidPrefab == null)
        {
            Debug.LogError("Boid prefab is not assigned!", this);
            return;
        }

        if (this.boidPrefab.GetComponent<Boid>() == null)
        {
            Debug.LogError("Boid prefab must have Boid component!", this);
            return;
        }

        // 添加碰撞体用于玩家检测（如果不存在）
        if (!GetComponent<Collider>())
        {
            var collider = gameObject.AddComponent<SphereCollider>();
            collider.isTrigger = true;
            collider.radius = orbitRadius * 1.5f;
        }

        // 开始生成鸟群
        GenerateBoids();

        // 启动边界检测
        boundaryCheckCoroutine = StartCoroutine(ContinuousBoundaryCheck());

        Debug.Log($"SpawnPoint at {transform.position} initialized with {this.boidCount} boids");
    }

    /// <summary>
    /// 生成初始鸟群
    /// </summary>
    // private void GenerateBoids()
    // {
    //     for (int i = 0; i < boidCount; i++)
    //     {
    //         // 在环绕半径内随机生成位置
    //         // Vector3 spawnPos = transform.position + Random.insideUnitSphere * spawnRadius;
    //         Vector3 spawnPos = transform.position + new Vector3(Random.insideUnitSphere.x, 0, Random.insideUnitSphere.z) * spawnRadius;

    //         // 实例化鸟对象
    //         GameObject boidObj = Instantiate(boidPrefab, spawnPos, Quaternion.identity);
    //         Boid boid = boidObj.GetComponent<Boid>();

    //         // 初始化鸟
    //         boid.Initialize(
    //             target: transform,
    //             orbitRadius: orbitRadius,
    //             orbitSpeed: orbitSpeed,
    //             targetWeight: attractionStrength,
    //             maxDistance: maxDistance,
    //             targetType: Boid.TargetType.SpawnPoint
    //         );

    //         managedBoids.Add(boid);
    //     }
    // }
    private void GenerateBoids()
    {
        // 先计算一个基础方向（可以随机或固定）
        Vector3 baseDirection = Random.insideUnitSphere.normalized;

        for (int i = 0; i < boidCount; i++)
        {
            // 1. 在球面上生成位置（而不是球体内）
            // 2. 添加一些随机扰动形成"条"状
            Vector3 spawnDirection = (baseDirection + Random.insideUnitSphere * 0.3f).normalized;
            Vector3 spawnPos = transform.position + spawnDirection * orbitRadius;

            // 3. 实例化鸟对象
            GameObject boidObj = Instantiate(boidPrefab, spawnPos, Quaternion.identity);
            Boid boid = boidObj.GetComponent<Boid>();

            // 4. 初始化时设置初始速度为切向速度（环绕方向）
            Vector3 initialVelocity = Vector3.Cross(spawnDirection, Vector3.up).normalized * orbitSpeed;

            // 5. 初始化鸟
            boid.Initialize(
                target: transform,
                orbitRadius: orbitRadius,
                orbitSpeed: orbitSpeed,
                targetWeight: attractionStrength,
                maxDistance: maxDistance,
                targetType: Boid.TargetType.SpawnPoint,
                initialVelocity: initialVelocity  // 添加新参数
            );

            managedBoids.Add(boid);
        }
    }

    /// <summary>
    /// 持续边界检查协程
    /// </summary>
    private IEnumerator ContinuousBoundaryCheck()
    {
        while (true)
        {
            if (managedBoids.Count > 0)
            {
                PerformBoundaryChecks();
            }
            yield return null; // 每帧执行
        }
    }

    /// <summary>
    /// 执行分帧边界检查
    /// </summary>
    private void PerformBoundaryChecks()
    {
        int checksDone = 0;

        for (int i = 0; i < managedBoids.Count && checksDone < checksPerFrame; i++)
        {
            int boidIndex = (currentCheckIndex + i) % managedBoids.Count;
            Boid boid = managedBoids[boidIndex];

            // 检查鸟是否有效
            if (boid == null || boid.gameObject == null)
            {
                managedBoids.RemoveAt(boidIndex);
                continue;
            }

            // 让鸟自己检查距离
            if (boid.CheckDistanceAndValidity())
            {
                RemoveBoid(boid, boidIndex);
            }

            checksDone++;
        }

        currentCheckIndex = (currentCheckIndex + 1) % Mathf.Max(1, managedBoids.Count);
    }

    /// <summary>
    /// 安全移除单个鸟
    /// </summary>
    private void RemoveBoid(Boid boid, int index)
    {
        if (index >= 0 && index < managedBoids.Count && managedBoids[index] == boid)
        {
            managedBoids.RemoveAt(index);
        }
        else
        {
            managedBoids.Remove(boid);
        }

        if (boid != null)
        {
            Destroy(boid.gameObject);
        }
    }

    /// <summary>
    /// 销毁所有鸟
    /// </summary>
    public void DestroyAllBoids()
    {
        if (boundaryCheckCoroutine != null)
        {
            StopCoroutine(boundaryCheckCoroutine);
        }

        foreach (Boid boid in managedBoids)
        {
            if (boid != null)
            {
                Destroy(boid.gameObject);
            }
        }
        managedBoids.Clear();
    }

    /// <summary>
    /// 当玩家触碰时转移所有鸟
    /// </summary>
    public void OnPlayerTouch(Transform player)
    {
        StartCoroutine(TransferBoidsToPlayer(player));
    }

    /// <summary>
    /// 协程：将鸟群转移给玩家
    /// </summary>
    private IEnumerator TransferBoidsToPlayer(Transform player)
    {

        // 禁用碰撞
        var collider = GetComponent<Collider>();
        if (collider != null) collider.enabled = false;

        // 转移每只鸟
        foreach (Boid boid in managedBoids)
        {
            if (boid != null)
            {
                // boid.FollowPlayer(player);
                yield return null; // 每帧转移一只鸟
            }
        }

        // 清理
        DestroyAllBoids();
        Destroy(gameObject, 0.1f); // 稍后销毁确保所有操作完成
    }

    /// <summary>
    /// 触发器检测玩家
    /// </summary>
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            OnPlayerTouch(other.transform);
        }
    }

    /// <summary>
    /// 当对象销毁时自动清理
    /// </summary>
    private void OnDestroy()
    {
        DestroyAllBoids();
    }

    /// <summary>
    /// 在编辑器中可视化环绕半径
    /// </summary>
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.cyan;
        Gizmos.DrawWireSphere(transform.position, orbitRadius);
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, spawnRadius);
    }
}